<template>
  <transition-group name="breadcrumb">
    <v-breadcrumbs :key="breadcrumbsKey" :items="breadcrumbsItems">
      <template v-slot:divider>
        <v-icon>mdi-chevron-right</v-icon>
      </template>
      <template v-slot:item="{ item }">
        <v-breadcrumbs-item
          :to="item.to"
          :disabled="item.disabled"
        >
          {{ item.text }}
        </v-breadcrumbs-item>
      </template>
    </v-breadcrumbs>
  </transition-group>
</template>

<script>
import pathToRegexp from 'path-to-regexp'

export default {
  name: 'Breadcrumbs',
  data() {
    return {
      breadcrumbsKey: new Date().getTime(),
      breadcrumbsItems: []
    }
  },
  watch: {
    $route(route) {
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]
      if (!this.isDashboard(first)) {
        matched = [{ path: '/dashboard', meta: { title: '管理中心' }}].concat(matched)
      }
      this.breadcrumbsKey = new Date().getTime()
      this.breadcrumbsItems = matched.map(item => {
        if (item.meta && item.meta.title && item.meta.breadcrumb !== false) {
          return {
            text: item.meta.title,
            disabled: false,
            to: item.path
          }
        }
      })
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
    },
    pathCompile(path) {
      const { params } = this.$route
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    }
  }
}
</script>

<style lang="scss" scoped>
.breadcrumb-enter-active,.breadcrumb-leave-active{
  transition:all .5s;
}
.breadcrumb-enter,.breadcrumb-leave-active{
  opacity:0;
  transform:translateX(20px);
}
.breadcrumb-move{
  transition:all .5s;
}
.breadcrumb-leave-active{
  position:absolute;
}
</style>
